#include <bpf/libbpf.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

static void read_trace_pipe()
{
    int trace_fd;

    trace_fd = open("/sys/kernel/debug/tracing/trace_pipe", O_RDONLY, 0);
    if (trace_fd < 0) {
        perror("Failed to open /sys/kernel/debug/tracing/trace_pipe");
        return;
    }

    while (1) {
        static char buf[4096];
        ssize_t sz;

        sz = read(trace_fd, buf, sizeof(buf) - 1);
        if (sz < 0) {
            perror("Failed to read /sys/kernel/debug/tracing/trace_pipe");
            return;
        }

        buf[sz] = 0;
        puts(buf);
    }
}

int main()
{
    struct bpf_object *obj;
    struct bpf_program *prog;

    obj = bpf_object__open_file("kern.o", NULL);
    if (!obj) {
        perror("Failed to open BPF object file");
        return -1;
    }

    if (bpf_object__load(obj)) {
        perror("Failed to load BPF object");
        return -1;
    }

    prog = bpf_object__find_program_by_name(obj, "bpf_prog");
    if (!prog) {
        fprintf(stderr, "Failed to find BPF program\n");
        return -1;
    }

    if (!bpf_program__attach(prog)) {
        perror("Failed to attach BPF program");
        return -1;
    }

    printf("Successfully attached BPF program. Reading trace_pipe...\n");

    read_trace_pipe();

    return 0;
}
